
package character_11_;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author Administrator
 */
public class Clerk1 {
    
    private int product = -1;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    
    public void setProduct(int product) throws InterruptedException{
        lock.lock();
        try {
            waitIfFull();
            this.product = product;
            System.out.println("生产者设定" + this.product);//"生产者设定" +　
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
    
    private void waitIfFull() throws InterruptedException {
        while (this.product != -1) {            
            condition.await();
        }
    }
    public int getProduct() throws InterruptedException{
    
        lock.lock();
        try {
            waitIfEmpty();
            int p = this.product;
            this.product = -1;
            System.out.println("消费者取走" + p);
            condition.signal();
            return p;
        } finally {
            lock.unlock();
        }
        
    }
    
    private void waitIfEmpty() throws InterruptedException{
    
        while (this.product == -1) {            
            condition.await();
        }
    }
}
